import { FC, useEffect, useMemo, useState } from "react";
import { useRequest } from "ahooks";
import { Picker } from "@tarojs/components";
import {
  fetchCityList,
  fetchDistrictList,
  fetchProvinceList,
} from "../service";
import { City, District, Province } from "../type";
// import { addressData } from "../config";

interface Props {
  onConfirm?: (value: [Province, City, District]) => void;
}

const AddressPicker: FC<Props> = ({ children, onConfirm }) => {
  const [provinceIndex, setProvinceIndex] = useState<number>(0);
  const [cityIndex, setCityIndex] = useState<number>(0);
  const [districtIndex, setDistrictIndex] = useState<number>(0);
  const [provinceList, setProvinceList] = useState<Province[]>([]);
  const [cityList, setCityList] = useState<City[]>([]);
  const [districtList, setDcistrictList] = useState<District[]>([]);

  useRequest(fetchProvinceList, {
    onSuccess(data) {
      if (data.res) {
        setProvinceList(data.res.records);
        queryCity(data.res.records[0].code);
      }
    },
  });
  const { run: queryCity } = useRequest(
    (provinceCode) => fetchCityList(provinceCode),
    {
      manual: true,
      onSuccess(data) {
        if (data.res) {
          setCityList(data.res.records);
          queryDistrict(data.res.records[0].code);
        }
      },
    }
  );
  const { run: queryDistrict } = useRequest(
    (cityCode) => fetchDistrictList(cityCode),
    {
      manual: true,
      onSuccess(data) {
        if (data.res) {
          setDcistrictList(data.res.records);
        }
      },
    }
  );

  const onSelected = (value: number[]) => {
    const province = provinceList[value[0]];
    const city = cityList[value[1]];
    const district = districtList[value[2]];
    onConfirm && onConfirm([province, city, district]);
  };

  /**选择列column列, value: 选中的值对应的下标*/
  const onChangeColumn = (e: { column: number; value: number }) => {
    if (e.column === 0) {
      const province = provinceList[e.value];
      setProvinceIndex(e.value);
      setCityIndex(0);
      queryCity(province.code);
    }
    if (e.column === 1) {
      const city = cityList[e.value];
      setCityIndex(e.value);
      setDistrictIndex(0);
      queryDistrict(city.code);
    }
  };

  return (
    <Picker
      mode="multiSelector"
      range={[provinceList, cityList, districtList]}
      rangeKey="name"
      value={[provinceIndex, cityIndex, districtIndex]}
      onColumnChange={(e) => onChangeColumn(e.detail)}
      onChange={(e) => onSelected(e.detail.value)}
    >
      {children}
    </Picker>
  );
};

export default AddressPicker;
